package confidence.helpers;


import java.util.Vector;

public class Assembler<SnapshotType extends SnapshotAss> {
	protected FactoryAss<SnapshotType> factory = null;
	protected Vector<SnapshotType> snapshots = new Vector<SnapshotType> ();
	
	public Assembler (FactoryAss<SnapshotType> pFactory) {
		factory = pFactory; 		
	}
	
	/**
	 * Add a tag to one of incomplete snapshots to assemble
	 * @param pTag Tag to add
	 * @param pLabel Label of the tag to add
	 * @param pClassVal Class of the tag to add; should be -1 if unknown
	 * @return A completed snapshot; the first snapshot if the list of snapshots to assemble is full; null otherwise
	 */
	public SnapshotType addTag (Tag pTag, String pLabel, String pClassVal) {
		boolean added = false;
		
		//Try to add the tag to one of the incomplete snapshots
		for (int i = 0; i < snapshots.size (); i++) {
			if (added = snapshots.elementAt (i).addTag (pTag, pLabel)) {
				//If the tag was added, remove and return the snapshot if complete
				//System.out.println (pTag + " added to " + snapshots.elementAt (i));
				if (snapshots.elementAt (i).isComplete ()) {
					snapshots.elementAt (i).createMissingTags ();
					//System.out.println (snapshots.elementAt (i) + " returned complete");
					snapshots.elementAt (i).computeDT ();
					return snapshots.remove (i);
				}
				break;
			}
		}
		//If the tag was not added...
		if (!added) {
			//If the list of snapshots is full, remove and return the first one
			if (snapshots.size () >= Status.getIntValue ("ASSEMBLY_SNAP_COUNT")) {
				snapshots.elementAt (0).createMissingTags ();
				//System.out.println (snapshots.elementAt (0) + " returned incomplete");
				snapshots.elementAt (0).computeDT ();
				return snapshots.remove (0);
			}
			//Add a new snapshot to the list
			SnapshotType newSnap = factory.create ();
			newSnap.addTag (pTag, pLabel);
			newSnap.setClass (pClassVal);
			//System.out.println (newSnap + " created");
			snapshots.add (newSnap);
		}
		return null;
	}
	
	/**
	 * Empty the queue of snapshots to assemble. Add an ampty snapshot to the queue and mark it as the first snapshot of a new recording. 
	 */
	public void setAfterBreak () {
		snapshots.clear ();
		SnapshotType newSnap = factory.create ();
		newSnap.setAfterBreak ();
		snapshots.add (newSnap);
	}
	
}
